2.8.單鏈表上的刪除操作算法
public void remove(int i) throws Exception {
? ? Node p = head; ? ? ? ? ? ? ? ? ? ? ? ? ? ?//初始化p指向頭結點,j為計數器
? ? int j = -1;
? ? while(p.next != null && j < i-1) { ? ? ? ?//尋找第i個結點的前驅
? ? ? ? p = p.next;
? ? ? ? ++j;
? ? }
? ? if (j > i-1 || p.next == null){
? ? ? ? throw new Exception("刪除位置不合法"); //修改指針,使待刪除結點從單鏈表中脫離出來
? ? p.next = p.next.next;
}?
3.3求鏈棧的長度操作算法
public int length() {
? ? Node p = top; ? ? ? ? ? ?//初始化,p指向棧頂元素,length為計數器
? ? int length = 0; ? ?
? ? while (p != null) { ? ? ?//從棧頂元素向后查找,直到p指向空
? ? ? ? p = p.next; ? ? ? ? ?//p指向后繼結點
? ? ? ? ++length; ? ? ? ? ? ?//長度加1
? ? }
? ? return length;
}?
3.4鏈棧的入棧操作算法
public void push(Object x) {
? ? Node p = new Node(x); ? ? ? ?//構造一個新結點
? ? p.next = top;
? ? top = p; ? ? ? ? ? ? ? ? ? ?//新結點成為當前的棧頂結點
}
3.5鏈棧的出棧操作算法
public Object pop() {
? ? ? ? if (isEmpty()) {
? ? ? ? ? ? return null;
? ? ? ? }
? ? ? ? else {
? ? ? ? ? ? Node p = top; ? ? ? ?//p指向被刪結點(棧頂結點)
? ? ? ? ? ? top = top.next; ? ? ?//修改鏈指針,使棧頂結點從鏈棧中移去
? ? ? ? ? ? return p.data; ? ? ? //返回棧頂結點的數據域的值
? ? ? ? }
}
3.6循環順序隊列的入隊操作算法
public void offer(Object x) throws Exception{
? ? if ((rear + 1) % queueElem.length == front) ?//隊列滿
? ? ? ? throw new Exception("隊列已滿"); ? ? ? ? ?//拋出異常
? ? else {
? ? ? ? queueElem[rear] = x;
?
? ? //x存入rear所指的數組存儲位置中,使其成為新的隊尾元素
? ??
? ? rear = (rear + 1) % queueElem.length; ? ? ? ?//修改隊尾指針
}
3.8 鏈隊列的入隊操作算法
public void offer(Object x) {
? ? Node p = new Node(x); ? ? ? ? ? ?//初始化隊列新結點
? ? if (front != null){ ? ? ? ? ? ? ?//隊列非空
? ? ? ? rear.next = p;
? ? ? ? rear = p; ? ? ? ? ? ? ? ? ? ?//改變隊尾的位置
? ? }
? ? else
? ? ? ? front = rear = p;
}